package com.share.alibaba.auser.http;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.share.common.common.Result;
import com.share.common.enums.ErrMsgEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class AEditorHttpClient {
    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "testHttpFallBack", ignoreExceptions = {Exception.class},
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "50")
            })
    public Result testHttp(String param) {
        String url = "http://www.sina.com.cn/api/hotword.json";
        String body = restTemplate.getForObject(url, String.class);
        log.info("请求结果body={}", body);
        return Result.success(body);
    }

    /**
     * HystrixCommand注解生效的时机是外部发起http请求并调用这个方法的时候，使用PostConstruct是无法触发的，因为httpselevtrequest对象为空
     * 回调方法的返回值与参数必须与别调用的一样（参数有且仅允许扩展一个Throwable参数）
     * @param param
     * @param throwable
     * @return
     */
    public Result testHttpFallBack(String param, Throwable throwable) {
        return testHttpFallBack(param);
    }

    public Result testHttpFallBack(String param) {
        return Result.failure(ErrMsgEnum.HYSTRIX_HAPPEN);
    }
}
